package com.hmall.search.listen;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.feign.ItemClient;
import com.hmall.search.pojo.Order;
import com.hmall.search.pojo.OrderDetail;
import com.hmall.search.service.IOrderService;
import com.hmall.search.service.OrderDetailService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Component
@EnableTransactionManagement
public class Orderlisten {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailService orderDetailService;


    //减库存
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue",durable = "true"),
            exchange = @Exchange(name = "delay.direct",delayed = "true"),
            key = "delay"
    ))
    public void listenDelayedQueue(String message){
        Long orderId = Long.valueOf(message);

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orderId);
        OrderDetail orderDetail = orderDetailService.getOne(queryWrapper);
        Order order = orderService.getById(orderId);
        Integer num = orderDetail.getNum();
        Long itemId = orderDetail.getItemId();

        Integer status = order.getStatus();

        if (status==1){
            itemClient.stock(itemId,num);
            order.setStatus(5);
            orderService.updateById(order);
        }
        return;

    }

}
